package org.intellij.doctree;

import org.intellij.doctree.node.DocTreeNode;

import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;

public class DocTreeModel extends DefaultTreeModel {

    public DocTreeModel(DocTreeNode root) {
        super(root, true);
        setAsksAllowsChildren(true);
    }

    public void moveNodeUp(DocTreeNode node) {
        DocTreeNode parent = (DocTreeNode) node.getParent();
        if (parent == null) return;
        int childIdx = parent.getIndex(node);
        if (childIdx < 1) return;

        removeNodeFromParent(node);
        insertNodeInto(node, parent, childIdx - 1);

    }

    public void moveNodeDown(DocTreeNode node) {
        DocTreeNode parent = (DocTreeNode) node.getParent();
        if (parent == null) return;
        int childIdx = parent.getIndex(node);
        if (childIdx >= parent.getChildCount() - 1) return;

        removeNodeFromParent(node);
        insertNodeInto(node, parent, childIdx + 1);

    }

    public void clear() {
        for (int i = root.getChildCount() - 1; i >= 0; i--) {
            MutableTreeNode treeNode = (MutableTreeNode) root.getChildAt(i);
            removeNodeFromParent(treeNode);
        }
    }

}
